package controller.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import dao.UserDao;
import factory.UserFactory;
import pojo.User;
import util.GetFileName;


@MultipartConfig(maxFileSize = 6666666, fileSizeThreshold = 1000)
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		String uploadDir = request.getServletContext().getRealPath("/images");
		Part part = request.getPart("picfile");
//		String realPath = request.getServletContext().getRealPath("/images");
//		System.out.println(realPath); //F:\apache-tomcat-9.0.10\webapps\MakeFriends\images
		if(part.getSubmittedFileName() != null && part.getSubmittedFileName() != "") {
			String header = part.getHeader("Content-Disposition");
			String fileName = GetFileName.getFileName(header);
			HttpSession session = request.getSession();
			String uname = (String)session.getAttribute("uname");
			String saveName = uname+fileName;
			part.write("F:\\Working\\eclipse-workspace\\javaWebTest\\MakeFriends\\WebContent\\images" + File.separator + saveName);
//			part.write(realPath + File.separator + fileName);
			try {
				UserDao userDao = UserFactory.getInstance("userdaoimpl", UserDao.class);				
//				System.out.println("这是session中的用户名:"+uname+"\nfileName:"+fileName);
				User user = userDao.getAppointUser(uname);
				userDao.updateUserPic(user, saveName);
			} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
				e.printStackTrace();
			}
			request.setAttribute("upic", fileName);
			request.getRequestDispatcher("view/index.jsp").forward(request, response);
		}else{
			PrintWriter out = response.getWriter();
			out.println("<script>alert('文件为空！');history.back();</script>") ;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}